package com.hcr.elecident;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hcr.entity.EWM;
import com.hcr.entity.ScaEntity;
import com.hcr.entity.WxResult;
import com.hcr.util.MacAddressManager;
import com.hcr.util.MyConst;
import com.hcr.util.Result;
import com.jia.jsesaypaylibrary.wxpay.WXPay;
import com.jia.jsesaypaylibrary.wxpay.WXPayConfig;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.io.IOException;
import java.net.URL;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ScanResultActivity extends AppCompatActivity {

    String content = "";
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_result);
        ActivityManager.getActivityManager().pushActivity(this);

        webView = (WebView) findViewById(R.id.scanresultpage);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(this, "nativeMethod");

        // 允许访问url
        webSettings.setAllowFileAccessFromFileURLs(true);


        // 增加localstore支持
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);


        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        content = getIntent().getStringExtra("content");

        try{
            EWM ewm = JSON.parseObject(content, EWM.class);
            //        酒店id传过来
//            System.out.println("??????????????:::" + ewm.getId());


            SharedPreferences pre = getSharedPreferences(WelcomeActivity.TEMP_DATA, MODE_PRIVATE);
            String id = pre.getString("id", null);

//            System.out.println("+++++++++++++++++用户id"+id);
            if (id != null) {
//                postDevice(Integer.parseInt(id), ewm.getId(),ewm.getType());
            }
            webView.loadUrl("file:///android_asset/10.html?id=" + ewm.getId());
        } catch (Exception e){
            webView.loadUrl("file:///android_asset/10.html?id=000000000000");
        }


    }

    @JavascriptInterface
    public void toActivity() {
        startActivity(new Intent(this, PageActivity.class));
    }


    @JavascriptInterface
    public boolean freeScan(String uid,String hid,String htype){
        finish();
        return postDevice(Integer.parseInt(uid), hid,htype);
    }



    /**
     * 微信支付
     */
    @JavascriptInterface
    public void wxPay(String uid,String hid,String totalFee,String htype) throws Exception {

//        System.out.println("开始支付========================");
        try{
            OkHttpClient client = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("hid", hid)
                    .add("totalFee", totalFee)
                    .add("uid", uid)
                    .add("attach","a,"+uid+","+hid+","+htype)
                    .build();

            Request request = new Request.Builder()
                    .url(new URL(MyConst.HT + "weixin/order"))
                    .post(body)
                    .build();

            Response response = client.newCall(request).execute();

            String responseData = response.body().string();

            WxResult result = JSON.parseObject(responseData, new WxResult().getClass());
//            System.out.println(result);

            if (!"".equals(result.getPrepayid()) || null != result.getPrepayid()) {
                PayReq req = new PayReq();
                req.appId = result.getAppid();
                req.partnerId = result.getPartnerid();
                req.prepayId = result.getPrepayid();
                req.packageValue = "Sign=WXPay";
                req.nonceStr = result.getNoncestr();
                req.timeStamp = result.getTimestamp();


                WXPayConfig.getInstance().setAPI_KEY(MyConst.API_KEY);
                WXPayConfig.getInstance().setAPP_ID(MyConst.APP_ID);
                WXPayConfig.getInstance().setMCH_ID(MyConst.MCH_ID);

                WXPay wxPay = new WXPay(ScanResultActivity.this);
                wxPay.pay(req.prepayId);
            } else {
                Toast.makeText(this,"服务异常",Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            Toast.makeText(this,"服务异常",Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    // 扫描信息给后台
    public boolean postDevice(int uid, String hId,String htype) {
        final boolean[] flag = {false};
        ScaEntity scaEntity = new ScaEntity(uid, hId,htype, MacAddressManager.getAdresseMAC(getApplicationContext()), Build.BRAND + " " + Build.MODEL);

//        System.out.println(":::::" + scaEntity.toString());
//        System.out.println("!!!" + MacAddressManager.getAdresseMAC(getApplicationContext()));

        OkHttpClient okHttpClient = new OkHttpClient();
        String json = JSON.toJSONString(scaEntity);
//        System.out.println("要发送的数据：" + json);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(MyConst.HT + "user/scan")//请求的url
                .post(requestBody)
                .build();
        okhttp3.Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                final String res = response.body().string();
                Result result = JSON.parseObject(res, Result.class);
                if (result.getCode() == 200){
                    flag[0] = true;
                }
            }
        });

        return flag[0];
    }


}
